package com.atguigu.day04;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Felix
 * @date 2024/4/2
 * 该案例演示了通过侧输出流实现分流操作
 * 需求：从指定的网络端口读取水位信息，将不同的传感器采集到的信息放到不同的流中
 */
public class Flink04_Split_Stream_SideOutput {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.从网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.对流中数据进行类型转换    String->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());
        //TODO 4.分流
        //定义侧输出流标签   注意：存在泛型擦除问题  通过匿名内部类方式创建对象或者在创建对象的时候，声明类型
        OutputTag<WaterSensor> ws1Tag = new OutputTag<WaterSensor>("ws1"){};
        OutputTag<WaterSensor> ws2Tag = new OutputTag<WaterSensor>("ws2", Types.POJO(WaterSensor.class));
        //分流   这里需要用到上下文对象，只能调用底层的处理函数process
        SingleOutputStreamOperator<WaterSensor> mainDS = wsDS.process(
                new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor ws, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        String id = ws.getId();
                        if ("ws1".equals(id)) {
                            //将数据"放到"侧输出流中---只是打了一个标记
                            ctx.output(ws1Tag, ws);
                        } else if ("ws2".equals(id)) {
                            ctx.output(ws2Tag, ws);
                        } else {
                            //将数据放到主流
                            out.collect(ws);
                        }
                    }
                }
        );
        //TODO 5.将不同流数据进行打印
        SideOutputDataStream<WaterSensor> ds1 = mainDS.getSideOutput(ws1Tag);
        SideOutputDataStream<WaterSensor> ds2 = mainDS.getSideOutput(ws2Tag);
        mainDS.print("主流");
        ds1.print("ws1");
        ds2.print("ws2");
        //TODO 6.提交作业
        env.execute();
    }
}
